package admin

import (
	"fmt"
	"github.com/astaxie/beego"
	"strings"
	"time"
	"xianzhi/service"
	"xianzhi/utils"
)

type BaseController struct {
	beego.Controller
}

func (c *BaseController) Prepare() {
	noLogin := map[string]string{
		"UserAdminControllerLogin": "1",
		"UserAdminControllerDoLogin": "1",
		"UserAdminControllerLogout": "1",
	}
	ctl, act := c.GetControllerAndAction()
	ctlAct := fmt.Sprintf("%s%s", ctl, act)
	_, ok := noLogin[ctlAct]
	if !ok {
		userAdminId := c.GetSession("userAdminId")
		if userAdminId == nil {
			c.Redirect("/admin/login", 302)
			return
		}

		p := map[string]interface{}{}
		p["id"] = userAdminId
		userAdmin := service.GetUserAdminInfo(p)
		if userAdmin.Id <= 0 {
			c.Redirect(beego.URLFor("admin.UserAdminController.Login"), 302)
			return
		}

		var res *utils.ResJsonStruct
		allAuthorityMap := utils.GetAuthorityMap()
		if userAdmin.UserAdminRole.Id > 1 {
			p = map[string]interface{}{}
			p["userAdminRoleId"] = userAdmin.UserAdminRole.Id
			_, authorityList := service.GetAuthorityList(p)
			if len(authorityList) <= 0 {
				res = utils.ResJson(0, "没有访问权限", "")
				c.Data["json"] = res
				c.ServeJSON()
				return
			}
			var authoritySlice []string
			for _, authority := range authorityList {
				allAuthorityMap[authority.Rule] = true
				authoritySlice = append(authoritySlice, authority.Rule)
			}
			authorityStr := strings.Join(authoritySlice, ",")
			if _, ok := allAuthorityMap[ctlAct]; ok {
				if !strings.Contains(authorityStr, ctlAct) {
					res = utils.ResJson(0, "没有访问权限", "")
					c.Data["json"] = res
					c.ServeJSON()
					return
				}
			}
		} else if userAdmin.UserAdminRole.Id == 1 {
			for k, _ := range allAuthorityMap {
				allAuthorityMap[k] = true
			}
		} else {
			res = utils.ResJson(0, "没有访问权限", "")
			c.Data["json"] = res
			c.ServeJSON()
			return
		}

		c.Data["allAuthorityMap"] = allAuthorityMap
		c.Data["loginUserAdmin"] = userAdmin
		c.Data["currentTime"] = time.Now().Format("2006-01-02 15:04")
	}
}